package com.hefan.activity.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.TradeLogAccountTypeEnum;
import com.cat.common.meta.TradeLogPayStatusEnum;
import com.cat.common.util.GuuidUtil;
import com.hefan.activity.bean.AppTaskInfo;
import com.hefan.activity.bean.AppTaskRelation;
import com.hefan.activity.dao.AppTaskInfoDao;
import com.hefan.activity.dao.AppTaskRelationDao;
import com.hefan.activity.itf.AppTaskService;
import com.hefan.pay.bean.TradeLog;
import com.hefan.pay.itf.TradeLogService;
import com.hefan.user.bean.WebUser;
import com.hefan.user.itf.WebUserService;

@Component("appTaskService")
public class AppTaskServiceImpl implements AppTaskService{

	@Resource
	AppTaskInfoDao appTaskInfoDao;
	@Resource
	AppTaskRelationDao appTaskRelationDao;
	@Resource
	WebUserService webUserService;
	@Resource
	TradeLogService tradeLogService;
	
	@Override
	public List<AppTaskInfo> getAppTaskInfoList() {
		// TODO Auto-generated method stub
		return appTaskInfoDao.getAppTaskInfoList();
	}

	@Override
	public AppTaskInfo getAppTaskInfoListByType(int type) {
		// TODO Auto-generated method stub
		String sql = "select * from app_task_info where task_type=?";
		List<Object> params = new ArrayList<Object>();
		params.add(type);
		return appTaskInfoDao.get(sql, params);
	}
	
	@Override
	public AppTaskRelation getAppTaskRelationByUserId(String userId) {
		// TODO Auto-generated method stub
		String sql = "select * from app_task_relation where user_id=?";
		List<Object> params = new ArrayList<Object>();
		params.add(userId);
		return appTaskRelationDao.get(sql, params);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public AppTaskRelation saveOrUpAppTaskRelation(AppTaskRelation appTaskRe) {
		// TODO Auto-generated method stub
		return appTaskRelationDao.save(appTaskRe);
	}

	@Override
	public Map<String,Object> getGiftUserNum(String userId, String toUserId, Date beginTime, Date endTime,int source) {
		// TODO Auto-generated method stub
		return appTaskInfoDao.getGiftUserNum(userId, toUserId, beginTime, endTime, source);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public int updateAppTaskStatus(AppTaskRelation appTaskRe, AppTaskInfo appTaskInfo) {
		// TODO Auto-generated method stub
		appTaskRelationDao.save(appTaskRe);
		if(appTaskInfo.getExpValue()>0){
			//加经验
			try {
				ResultBean res = webUserService.userLevelOprate(appTaskRe.getUserId(), appTaskInfo.getExpValue());
				if(res.getCode() !=1000){
					throw new RuntimeException("加经验失败");
				}
			}catch (Exception e){
				//加经验失败主动抛出异常
				e.printStackTrace();
				throw new RuntimeException("加经验失败");
			}
		}
		if(appTaskInfo.getTicketValue()>0){
			//加饭票
			try {
				WebUser webUser = webUserService.findMyUserInfo(appTaskRe.getUserId());
				//新增用户饭票
				int rowNum = webUserService.incrWebUserBalance(appTaskRe.getUserId(),appTaskInfo.getTicketValue());
				if(rowNum > 0) {
				    //保存充值信息
				    TradeLog tradeLog = new TradeLog();
				    tradeLog.setOrderId(GuuidUtil.getUuid());
				    tradeLog.setUserId(appTaskRe.getUserId());
				    tradeLog.setUserType(webUser.getUserType());
				    tradeLog.setNickName(webUser.getNickName());
				    tradeLog.setPayAmount(new BigDecimal(0));
				    tradeLog.setIncome(0);
				    tradeLog.setExchangeAmount(new BigDecimal(0));
				    tradeLog.setChannelFee(new BigDecimal(0));
				    tradeLog.setPlatformCost(new BigDecimal(0));
				    tradeLog.setIncomeAmount(appTaskInfo.getTicketValue());
				    tradeLog.setRewardFanpiao(appTaskInfo.getTicketValue());
				    tradeLog.setAccountType(TradeLogAccountTypeEnum.TASK_CODE_ACCOUNT_TYPE.getAccountType());
				    tradeLog.setPaySource(0);
				    tradeLog.setPayBeforeFanpiao(webUser.getBalance());
				    tradeLog.setPayAfterFanpiao(webUser.getBalance()+appTaskInfo.getTicketValue());
				    tradeLog.setPayStatus(TradeLogPayStatusEnum.PAY_SUCCESS.getPayStatus());
				    tradeLog.setPaymentExtend(JSON.toJSONString(appTaskRe));
				    tradeLog.setPaymentType(0);
				    tradeLog.setThirdPartyTradeNo(String.valueOf(appTaskInfo.getId()));
				    tradeLogService.saveAndCalTradeLog(tradeLog);
				}else{
					//加饭票失败主动抛出异常
					throw new RuntimeException(webUser.getUserId()+"加经验失败，任务类型:"+appTaskInfo.getTaskType());
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				//加饭票失败主动抛出异常
				throw new RuntimeException("加饭票失败");
			}
		}
		return 1;
	}

}
